package es.us.idinfor.rmplugin.example;

import java.util.Arrays;
import java.util.List;

import com.rapidminer.example.Attribute;
import com.rapidminer.example.table.DataRow;
import com.rapidminer.example.table.DataRowReader;
import com.rapidminer.example.table.DoubleArrayDataRow;
import com.rapidminer.example.table.ExampleTable;
import com.rapidminer.example.table.MemoryExampleTable;
import com.rapidminer.operator.OperatorException;

public class OptimizedMemoryExampleTable extends MemoryExampleTable {
	private static final long serialVersionUID = 3186274552407204195L;
	
	public OptimizedMemoryExampleTable(List<Attribute> attributes) {
		super(attributes);
	}
	
	public static OptimizedMemoryExampleTable createCompleteCopy(ExampleTable es) {
        OptimizedMemoryExampleTable table = new OptimizedMemoryExampleTable(Arrays.asList(es.getAttributes()));
        DataRowReader reader = es.getDataRowReader();
        DataRow dataRow = null;
        double[] newDataRowData = null;
        Attribute attribute = null;
        
        while(reader.hasNext()) {
            dataRow = reader.next();
            newDataRowData = new double[es.getNumberOfAttributes()];
        	
        	for(int a = 0; a < es.getNumberOfAttributes(); a++) {
                attribute = es.getAttribute(a);
                newDataRowData[a] = dataRow.get(attribute);
            }
            
            table.addDataRow(new DoubleArrayDataRow(newDataRowData));
        }
        
        attribute = null;
        newDataRowData = null;
        dataRow = null;
        reader = null;
        
        return table;
    }
	
	public static OptimizedMemoryExampleTable createSubCopy(ExampleTable es, String labelName, double labelValue) throws OperatorException {
        OptimizedMemoryExampleTable table = new OptimizedMemoryExampleTable(Arrays.asList(es.getAttributes()));
        Attribute label = es.findAttribute(labelName);
        DataRowReader reader = es.getDataRowReader();
        DataRow dataRow = null;
        double[] newDataRowData = null;
        Attribute attribute = null;
        
        while(reader.hasNext()) {
            dataRow = reader.next();
            
            if(dataRow.get(label) == labelValue) {
            	newDataRowData = new double[es.getNumberOfAttributes()];
            	
            	for(int a = 0; a < es.getNumberOfAttributes(); a++) {
                    attribute = es.getAttribute(a);
                    newDataRowData[a] = dataRow.get(attribute);
                }
                
                table.addDataRow(new DoubleArrayDataRow(newDataRowData));
            }
        }
        
        attribute = null;
        newDataRowData = null;
        dataRow = null;
        reader = null;
        label = null;
        
        return table;
    }
}
